import axios from 'axios'
import store from '@/store'
import { Toast } from 'vant'
import constant from '@/constant/httpStatus'

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
const instance = axios.create({
  timeout: 10000
})
instance.defaults.baseURL = constant.API_BASE_URL
// request拦截器
instance.interceptors.request.use(config => {
  // Do something before request is sent
  if (store.getters.token) {
    config.headers.authorization = store.getters.token // 让每个请求携带token--['X-Token']为自定义key 请根据实际情况自行修改
  }
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})
// respone 拦截器
instance.interceptors.response.use(res => {
  if (res.status === 200) {
    const data = res.data
    if (constant.SUCCESS === data.code) {
      return data
    } else {
      Toast.fail(data.msg)
      return data
    }
    // returnCode(data)
  }
}, error => {
  Toast.fail(error.message)
  return Promise.reject(error)
}
)

export default instance
